#include <stdio.h>
#include "linklist.h"

/*get the index element*/
Status GetElem(LinkList L, int i, ElemType *e)
{
    int cnt;
    LinkList p;
    cnt = 1;
    while (p && cnt < i)
    {
        p = p->next;
        ++cnt;
    }

    if (!p || cnt > i)
    {
        return ERROR;
    }

    *e = p->data;
    return OK;
}

/*insert element before index*/
Status LinkInsert(LinkList *L, int i, ElemType e)
{
    int cnt;
    LinkList p, s;
    p = *L;
    cnt = 1;
    while (p && cnt < i)
    {
        p = p->next;
        cnt++;
    }

    if (!p || cnt > i)
    {
        return ERROR;
    }

    s = (LinkList)malloc(sizeof(Node));
    s->data = e;
    s->next = p->next;
    p->next = s;
    return OK;
}

/*Delete the index element*/
Status ListDelete(LinkList *L, int i, ElemType *e)
{
    int cnt;
    LinkList p, pCurent;
    p = *L;
    cnt = 1;
    while (p->next && cnt < i)
    {
        p = p->next;
        ++cnt;
    }

    if (!(p->next) || cnt > i)
    {
        return ERROR;
    }

    pCurent = p->next;
    p->next = pCurent->next;
    *e = pCurent->data;
    free(pCurent);
    return OK;
}

/*generate n element, create linklist with head node*/
void CreateListHead(LinkList *L, int n)
{
    LinkList p;
    int i;
    srand(time(0));
    *L = (LinkList)malloc(sizeof(Node));
    (*L)->next = NULL;

    for (i = 0; i < n; i++)
    {
        p = (LinkList)malloc(sizeof(Node));
        p->data = rand() % 100 + 1;
        p->next = (*L)->next;
        (*L)->next = p;
    }
}

/*random generate n element, create linklist with head node,(tail method)*/
void CreateListTail(LinkList *L, int n)
{
    LinkList p, rail;
    int i;
    srand(time(0));
    *L = (LinkList)malloc(sizeof(Node));
    rail = *L;
    for (i = 0; i < n; i++)
    {
        p = (Node*)malloc(sizeof(Node));
        p->data = rand() % 100 + 1;
        rail->next = p;
        rail = p;
    }

    rail->next = NULL;
}

/*Clear linklist*/
Status ClearList(LinkList *L)
{
    LinkList p, pCurent;
    p = (*L)->next;
    while (p)
    {
        pCurent = p->next;
        free(p);
        p = pCurent;
    }

    (*L)->next = NULL;
    return OK;
}

